package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.example.mapper.UserMapper;
import org.example.pojo.entity.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 内存中存放验证码 (实际项目中建议使用Redis或数据库存储，并加入过期时间处理)
    private Map<String, String> codeStore = new ConcurrentHashMap<>();

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username)) != null;
    }

    @Override
    public String generateVerificationCode() {

        // 生成一个4位数字验证码
        return String.valueOf((int)(Math.random() * 9000) + 1000);
    }

    @Override
    public void saveVerificationCode(String email, String code) {
        redisTemplate.opsForValue().set("emailVerificationCode" + email, code, 5, TimeUnit.MINUTES);
    }

    @Override
    public boolean verifyCode(String email, String code) {
        return Objects.equals(redisTemplate.opsForValue().get("emailVerificationCode" + email), code);
    }

    @Override
    public void registerNewUser(String username, String password, String email) {
        User user = new User();
        user.setUserId(String.valueOf(UUID.randomUUID()));
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setStatus(1);
        userMapper.insert(user);
    }

    @Override
    public User findByAccount(String account) {
        // 如果包含 "@"，则认为是邮箱登录；否则认为是用户名登录
        if (account.contains("@")) {
            // 根据邮箱查询用户（实际项目中替换为具体查询方法）
            return userMapper.selectOne(new QueryWrapper<User>().eq("email", account));
        } else {
            // 根据用户名查询用户
            return userMapper.selectOne(new QueryWrapper<User>().eq("username", account));
        }
    }

    @Override
    public User findById(long id){
        return userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
    }

}
